//Nathan Popham
//4003-573-01: Procedural Shading
//Lab 5
//
//lightShader.vert
// Frag shader for phong-shaded surface with spotlight.
//
// intensity -- color of light
// field -- field angle in degrees(maximum spotlight angle)
// beam -- beam angle in degrees (brightest section angle)
// from -- location of light
// to -- point spotlight is aiming at
// distance -- if >= 0.0, no distance attenuation; otherwise, 1/.3*d attenuation

varying vec3 P, N, L, eye, lightPos;

uniform vec3 intensity;
uniform float field;
uniform float beam;
uniform vec3 from;
uniform vec3 to;
uniform float distance; 

#define PI 3.14159

void main (void)
{
    vec3 temp = P; 
	temp = lightPos;
    vec4 LightSource = vec4 (0.0, 0.0, 0.0, 0.0);
  
    vec3 axis = normalize(to - from);
    axis = normalize(vec3(0.0, 0.0, 2.0));
    vec3 V = normalize(lightPos - P);
    
    float angle = abs(acos(dot(V, axis))) * 180.0 / PI;

    float distAttenuation = (distance > 0.0 ? .3*sqrt(dot(L, L)) : 1.0);

    if(angle <= beam)
        LightSource = vec4(intensity * (1.0 - .5*angle/beam) / distAttenuation, 1.0);
    else if(angle <= field)
        LightSource = vec4(intensity * (.5 - .4*(angle-beam)/(field-beam)) / distAttenuation, 1.0);
    else
        LightSource = vec4(0.0, 0.0, 0.0, 0.0);
  

    //phong bit
    vec4 final_color = vec4(0.2, 0.2, 0.0, 1.0);
							
	vec3 Nn = normalize(N);
	vec3 Ln = normalize(L);
	
	float lambertTerm = dot(Nn,Ln);

	vec4 diffuse = vec4 (0.8, 0.8, 0.0, 1.0);
	vec4 specColor = vec4 (1.0, 1.0, 1.0, 1.0);
	float shininess = 50.0;
	
	if(lambertTerm > 0.0)
	{
		//final_color += LightSource * diffuse * lambertTerm;
        final_color += diffuse * lambertTerm;		  
            		
		vec3 E = normalize(eye);
		vec3 R = reflect(-Ln, Nn);
		float specular = pow( max(dot(R, E), 0.0), shininess);
		final_color += specColor * specular;
		               	
	}

	gl_FragColor = final_color * LightSource;	
}
